package tk.mybatis.springboot.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * Created by Administrator on 2016/7/26.
 * 客户端请求处理 工具
 */
public class ServerUtil {

    private static Logger logger = LoggerFactory.getLogger(ServerUtil.class);

    private ServerUtil() {

    }

    public static HttpServletRequest getHttpServletRequest() {

        if(null== RequestContextHolder.getRequestAttributes()){
            return  null;
        }
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static HttpServletResponse getHttpServletResponse() {
        if(null== RequestContextHolder.getRequestAttributes()){
            return  null;
        }
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

    }


    public static boolean isAjax() {
        return "XMLHttpRequest".equalsIgnoreCase(getHttpServletRequest().getHeader("X-Requested-With"));
    }

    public static void sendMessage(int code, CharSequence charSequence) {
        HttpServletResponse response = getHttpServletResponse();
        response.setStatus(code);
        String value = charSequence.toString();
        try {
            byte[] data = value.getBytes("UTF-8");
            response.setContentLengthLong(data.length);
            response.setContentType("application/json");
            OutputStream os = null;
            try {
                os = response.getOutputStream();
                os.write(data);
                os.flush();
            } catch (Exception ex) {
                logger.error(ex.getMessage());
            } finally {
                if (null != os) {
                    try {
                        os.close();
                        os = null;
                        response = null;
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return;


    }

    public static void sendMessage(int code, Object object) {
        try {
            sendMessage(code, new ObjectMapper().writeValueAsString(object));
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }


    }
}
